package io.github.uicdb.badskill.codec;

import com.google.gson.*;
import io.github.uicdb.badskill.SkillPage;
import net.minecraft.resources.ResourceLocation;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

public class MapLocationCodec implements JsonSerializer<Map<ResourceLocation, SkillPage.Location>>, JsonDeserializer<Map<ResourceLocation, SkillPage.Location>> {
    public static final MapLocationCodec INSTANCE=new MapLocationCodec();
    @Override
    public Map<ResourceLocation, SkillPage.Location> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        Map<ResourceLocation, SkillPage.Location> map=new HashMap<>();
        json.getAsJsonArray().forEach(element -> {
            JsonObject o=element.getAsJsonObject();
            ResourceLocation id=context.deserialize(o.get("id"),ResourceLocation.class);
            SkillPage.Location location=context.deserialize(o.get("location"), SkillPage.Location.class);
            map.put(id,location);
        });
        return map;
    }

    @Override
    public JsonElement serialize(Map<ResourceLocation, SkillPage.Location> src, Type typeOfSrc, JsonSerializationContext context) {
        JsonArray array=new JsonArray();
        src.forEach((resourceLocation, location) -> {
            JsonObject object=new JsonObject();
            object.add("id",context.serialize(resourceLocation,ResourceLocation.class));
            object.add("location",context.serialize(location, SkillPage.Location.class));
            array.add(object);
        });
        return array;
    }
}
